package cn.net.wanji.service.iml;

import cn.hutool.core.util.ObjectUtil;
import cn.net.wanji.config.ApplicationConfig;
import cn.net.wanji.config.RefreshSignageDataJob;
import cn.net.wanji.entity.*;
import cn.net.wanji.entity.deviceInfo.DeviceInfo;
import cn.net.wanji.entity.deviceStatus.DeviceStatus;
import cn.net.wanji.mapper.DataReceiveMapper;
import cn.net.wanji.mapper.MyDeviceInfoMapper;
import cn.net.wanji.mapper.SiteInfoMapper;
import cn.net.wanji.service.DataCopyService;
import cn.net.wanji.service.DataReceiveService;
import cn.net.wanji.utils.*;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.net.wanji.config.CommonParamConfig.AUDIT_ANOMALIES;
import static cn.net.wanji.config.CommonParamConfig.AUDIT_IS_NORMAL;

/**
 * @author guodejun
 * @createTime 2022/10/28 10:20
 * @description
 */
@Log4j2
@Service
public class DataReceiveServiceImpl implements DataReceiveService {

    @Resource
    DataReceiveMapper dataReceiveMapper;
    @Resource
    SiteInfoMapper siteInfoMapper;

    @Resource
    ApplicationConfig applicationConfig;

    @Resource
    SaveFileUtils saveFileUtils;
    @Override
    public void dataReceive(JsonRoot jsonRoot) {
        String fileNginx = applicationConfig.getFileNginx(jsonRoot.getRecordId());
        VehicleRsuInfo vehicleRsuInfo = jsonRoot.getVehicleRsuInfo(fileNginx);
        String unlawfulMold = vehicleRsuInfo.getUnlawfulMold();
        if (StringUtils.isNotNull(vehicleRsuInfo.getSidePicTime())&& !"2000-01-01 00:00:00".equals(vehicleRsuInfo.getSidePicTime())){
            vehicleRsuInfo.setExitTime(vehicleRsuInfo.getSidePicTime());
        } else if (StringUtils.isNotNull(vehicleRsuInfo.getHeadPicTime())&&!"2000-01-01 00:00:00".equals(vehicleRsuInfo.getHeadPicTime())) {
            vehicleRsuInfo.setExitTime(vehicleRsuInfo.getHeadPicTime());
        } else if (StringUtils.isNotNull(vehicleRsuInfo.getEtcTransTime())&&!"2000-01-01 00:00:00".equals(vehicleRsuInfo.getEtcTransTime())) {
            vehicleRsuInfo.setExitTime(vehicleRsuInfo.getEtcTransTime());
        }else {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            vehicleRsuInfo.setExitTime(format.format(new Date()));
        }
        //如果为C类数据标识etc缺失需要审核
        if("C".equals(vehicleRsuInfo.getRecordType())){
            // 添加 审核信息
            InspectionStatus inspectionStatus = new InspectionStatus();

            inspectionStatus.setRecordId(vehicleRsuInfo.getRecordId());
            inspectionStatus.setUnlawfulMold(vehicleRsuInfo.getUnlawfulMold());
            inspectionStatus.setCheckCondition("0");
            inspectionStatus.setConfidenceDegree(vehicleRsuInfo.getConfidenceDegree());

            dataReceiveMapper.insertInspectionStatus(inspectionStatus);
        }
        //A类数据
        if("A".equals(vehicleRsuInfo.getRecordType())){
            // 添加 审核信息
            InspectionStatus inspectionStatus = new InspectionStatus();

            inspectionStatus.setRecordId(vehicleRsuInfo.getRecordId());
            inspectionStatus.setUnlawfulMold(vehicleRsuInfo.getUnlawfulMold());
            inspectionStatus.setCheckCondition("0");
            inspectionStatus.setConfidenceDegree(vehicleRsuInfo.getConfidenceDegree());

            dataReceiveMapper.insertInspectionStatus(inspectionStatus);
        }
        if (ObjectUtil.isNotEmpty(unlawfulMold) && unlawfulMold.contains(",")) {
            for (String mold : unlawfulMold.split(",")) {
                vehicleRsuInfo.setUnlawfulMold(mold);
                dataReceiveMapper.insertVehicleRsuInfo(vehicleRsuInfo);


                String licenseCode = vehicleRsuInfo.getLicenseCode();
                if ("默A00000".equals(licenseCode)) {
                    vehicleRsuInfo.setUnlawfulMold("010501");
                }

                // 模拟置信度数据
                if (applicationConfig.getMockConfidenceDegree()) {
                    String randomPercentage = StringUtils.getRandomPercentage();
                    vehicleRsuInfo.setConfidenceDegree(randomPercentage);
                }

                // 只有车型异常的数据需要审核信息
                if (!StringUtils.isEmpty(vehicleRsuInfo.getUnlawfulMold()) && vehicleRsuInfo.getUnlawfulMold().startsWith("0102")) {
                    // 添加 审核信息
                    InspectionStatus inspectionStatus = new InspectionStatus();

                    inspectionStatus.setRecordId(vehicleRsuInfo.getRecordId());
                    inspectionStatus.setUnlawfulMold(vehicleRsuInfo.getUnlawfulMold());
                    inspectionStatus.setCheckCondition("0");
                    inspectionStatus.setConfidenceDegree(vehicleRsuInfo.getConfidenceDegree());

                    dataReceiveMapper.insertInspectionStatus(inspectionStatus);
                }
            }
        } else {
//            dataReceiveMapper.insertVehicleRsuInfo(vehicleRsuInfo);
            dataReceiveMapper.insertVehicleRsuInfo(vehicleRsuInfo);

            // recordType=A 为A类数据，没有识别信息，定义为 无号牌(平台自己定义)
            //        String recordType = vehicleRsuInfo.getRecordType();
            //        if ("A".equals(recordType)) {
            //            vehicleRsuInfo.setUnlawfulMold("010501");
            //        }
            // licenseCode(识别车牌)为"默A00000", 定义为无号牌(平台自定义)
            String licenseCode = vehicleRsuInfo.getLicenseCode();
            if ("默A00000".equals(licenseCode)) {
                vehicleRsuInfo.setUnlawfulMold("010501");
            }

            // 模拟置信度数据
            if (applicationConfig.getMockConfidenceDegree()) {
                String randomPercentage = StringUtils.getRandomPercentage();
                vehicleRsuInfo.setConfidenceDegree(randomPercentage);
            }

            // 只有车型异常的数据需要审核信息
            if (!StringUtils.isEmpty(vehicleRsuInfo.getUnlawfulMold()) && vehicleRsuInfo.getUnlawfulMold().startsWith("0102")) {
                // 添加 审核信息
                InspectionStatus inspectionStatus = new InspectionStatus();

                inspectionStatus.setRecordId(vehicleRsuInfo.getRecordId());
                inspectionStatus.setUnlawfulMold(vehicleRsuInfo.getUnlawfulMold());
                inspectionStatus.setCheckCondition("0");
                inspectionStatus.setConfidenceDegree(vehicleRsuInfo.getConfidenceDegree());

                dataReceiveMapper.insertInspectionStatus(inspectionStatus);
            }
        }
    }

    @Override
    public void saveFile(MultipartFile[] multipartFiles, Integer[] fileTypes, String recordId, String unlawfulMold, String detectTime) {
        log.info(detectTime);
        String time = DateUtils.getStrFormatYyyyMmdd(detectTime);
//        String time = recordId.substring(19, 27);
        String fileSavePath = "";
        if (StringUtils.isEmpty(unlawfulMold)) {
            //稽核正常
            fileSavePath = applicationConfig.getFileSavePath(recordId) + AUDIT_IS_NORMAL + File.separator + time + File.separator + recordId;
        } else {
            //稽核异常
            fileSavePath = applicationConfig.getFileSavePath(recordId) + AUDIT_ANOMALIES + File.separator + time + File.separator + recordId;
        }


        try {
            List<SaveFailInfo> saveFailInfos = new ArrayList<>();
            for (int i = 0; i < multipartFiles.length; i++) {
                MultipartFile multipartFile = multipartFiles[i];
                Integer fileType = fileTypes[i];
                String fileName = fileSavePath + File.separator + fileType;
                byte[] bytes = multipartFile.getBytes();
                SaveFailInfo saveFailInfo = new SaveFailInfo(bytes, fileType, fileName);
                saveFailInfos.add(saveFailInfo);
            }
            // 开启存储线程，存储文件


            this.saveFileUtils.saveFile(saveFailInfos, fileTypes, fileSavePath, recordId,detectTime);
        } catch (Exception e) {
            LogUtils.errorLog(e);
            e.printStackTrace();
        }

    }

    /**
     * 接受设备详情
     *
     * @param deviceInfo
     */
    @Override
    public void deviceInfoData(DeviceInfo deviceInfo) {
        List<MyDeviceInfo> myDeviceInfos = deviceInfo.getMyDeviceInfoList();
        insertOrUpdateMyDeviceInfo(myDeviceInfos);
    }


    /**
     * 接收设备状态信息
     *
     * @param deviceStatus
     */
    @Override
    public void deviceStatusData(DeviceStatus deviceStatus) {
        List<MyDeviceInfo> myDeviceInfos = deviceStatus.getMyDeviceInfoList();
        insertOrUpdateMyDeviceInfo(myDeviceInfos);
    }

    @Override
    public List<SiteInfo> listAllSiteInfos(SiteInfo siteInfo) {
        return siteInfoMapper.selectAllSiteInfos(siteInfo);
    }

    @Resource
    MyDeviceInfoMapper myDeviceInfoMapper;

    private void insertOrUpdateMyDeviceInfo(List<MyDeviceInfo> myDeviceInfos) {
        MyDeviceInfoExample example = new MyDeviceInfoExample();
        myDeviceInfos.forEach(item -> {
            example.clear();
            MyDeviceInfoExample.Criteria criteria = example.createCriteria();
            criteria.andSiteCodeEqualTo(item.getSiteCode());
            criteria.andDeviceCodeEqualTo(item.getDeviceCode());
            criteria.andDeviceTypeCodeEqualTo(item.getDeviceTypeCode());
            long count = myDeviceInfoMapper.countByExample(example);
            // 插入数据
            String obj = JSON.toJSONString(item);
            if (count == 0) {
                log.info("insert：" + obj);
                myDeviceInfoMapper.insert(item);
            } else {
                log.info("updateByExampleSelective：" + obj);
                myDeviceInfoMapper.updateByExampleSelective(item, example);
            }
        });
    }
}
